package synch2;

public class Bank {

    private final double[] accounts;

    public Bank(int n, double initialBalance) {
        this.accounts = new double[n];
        for (int i = 0; i < this.accounts.length; i++) {
            this.accounts[i] = initialBalance;
        }
    }

    public synchronized void transfer(int from, int to, double amount) throws InterruptedException {
        while (this.accounts[from] < amount) {
            wait();
        }
        System.out.print(Thread.currentThread());
        this.accounts[from] -= amount;
        System.out.printf(" %10.2f from %d to %d", amount, from, to);
        this.accounts[to] += amount;
        System.out.printf(" Total Balance: %10.2f\n", getTotalBalance());
        notifyAll();
    }

    public synchronized double getTotalBalance() {
        double sum = 0;
        for (double account : accounts) {
            sum += account;
        }
        return sum;
    }

    public int size() {
        return this.accounts.length;
    }
}
